package com.kpmg.datalake.web.interceptor;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.kpmg.datalake.common.utils.ContextHolderUtils;
import com.kpmg.datalake.common.utils.LogUtils;
import com.kpmg.datalake.db.model.SysUsr;
import java.util.Date;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * @since Created on azhao6 on 2018-07-30 10:20:11
 */
public class MyMetaObjectHandler extends MetaObjectHandler {
    /**
     * 创建人ID
     */
    private static final String CRT_USR_ID = "crtUsrId";
    /**
     * 创建时间
     */
    private static final String CRT_DT = "crtDt";
    /**
     * 更新人ID
     */
    private static final String UDT_USR_ID = "udtUsrId";
    /**
     * 更新时间
     */
    private static final String UDT_DT = "udtDt";

    /**
     * mybatis-plus 新增时自动填充 创建人 创建时间
     *
     * @param metaObject 操作对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (RequestContextHolder.getRequestAttributes() != null) {
            try {
                SysUsr user = ContextHolderUtils.getLoginUser();
                if (metaObject.hasGetter(MyMetaObjectHandler.CRT_USR_ID) && user != null
                    && super.getFieldValByName(MyMetaObjectHandler.CRT_USR_ID, metaObject)
                    == null) {
                    super.setFieldValByName(MyMetaObjectHandler.CRT_USR_ID, user.getUsrName(),
                        metaObject);
                }
            } catch (Exception e) {
                LogUtils.error(e.getMessage());
            }
        }
        if (metaObject.hasGetter(MyMetaObjectHandler.CRT_DT)
            && super.getFieldValByName(MyMetaObjectHandler.CRT_DT, metaObject) == null) {
            super.setFieldValByName(MyMetaObjectHandler.CRT_DT, new Date(), metaObject);
        }

    }

    /**
     * mybatis-plus 更新时自动填充 更新人 更新时间
     *
     * @param metaObject 操作对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (RequestContextHolder.getRequestAttributes() != null) {
            try {
                SysUsr user = ContextHolderUtils.getLoginUser();
                if (metaObject.hasGetter(MyMetaObjectHandler.UDT_USR_ID) && user != null
                    && super.getFieldValByName(MyMetaObjectHandler.UDT_USR_ID, metaObject)
                    == null) {
                    this.setFieldValByName(MyMetaObjectHandler.UDT_USR_ID, user.getUsrName(),
                        metaObject);
                }
            } catch (Exception e) {
                LogUtils.error(e.getMessage());
            }
        }

        if (metaObject.hasGetter(MyMetaObjectHandler.UDT_DT)
            && super.getFieldValByName(MyMetaObjectHandler.UDT_DT, metaObject) == null) {
            super.setFieldValByName(MyMetaObjectHandler.UDT_DT, new Date(), metaObject);
        }
    }
}